import config from '@/config'
import {getToken} from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import {showConfirm, tansParams, toast} from '@/utils/common'
import {RequestConfig, ResponseData} from '@/types/request'
import useUserStore from '@/store/modules/user'

let timeout = 10000
const baseUrl = config.baseUrl
const clientId = config.clientID;

let handling401Promise : Promise<void> | null = null; // 存储当前正在处理401的Promise

const handle401Error = () : Promise<void> => {
	if (handling401Promise) {
		console.log(1)
		// 如果已经有处理401的Promise存在，则返回该Promise
		return handling401Promise;
	}

	// 创建一个新的Promise来处理401错误
	const promise = new Promise<void>((resolve, reject) => {
		showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then(res => {
			if (res.confirm) {
				useUserStore().logOut().then(() => {
					uni.reLaunch({ url: '/pages/login' });
				}).finally(() => {
					// 处理完401后，重置Promise
					handling401Promise = null;
					resolve();
				});
			} else {
				// 用户选择不重新登录，直接重置Promise
				handling401Promise = null;
				resolve();
			}
		}).catch(() => {
			// 捕获任何可能的异常情况，重置Promise
			handling401Promise = null;
			reject();
		});
	});

	// 将新创建的Promise赋值给handling401Promise
	handling401Promise = promise;

	return promise;
};


const request = <T>(config : RequestConfig) : Promise<ResponseData<T>> => {
	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	config.header = config.header || {}
	if (getToken() && !isToken) {
		config.header['Authorization'] = 'Bearer ' + getToken()
		config.header['clientid'] = clientId
	}
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	if (config.header['Content-Type'] === 'multipart/form-data') {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				header: {
					Authorization: config.header['Authorization']
				},
				timeout: config.timeout || timeout,
				url: config.baseUrl || baseUrl + config.url,
				filePath: config.filePath,
				name: config.name,
				formData: config.data
			}).then(response => {
				handleResponse(response, resolve, reject);
			}).catch((error) => handleError(error, reject))
		})
	}

	return new Promise((resolve, reject) => {
		uni.request({
			method: config.method || 'GET',
			timeout: config.timeout || timeout,
			url: config.baseUrl || baseUrl + config.url,
			data: config.data,
			header: config.header,
			dataType: 'json'
		}).then(response => {
			handleResponse(response, resolve, reject);
		}).catch((error) => handleError(error, reject))
	})
}

function handleResponse(response : any, resolve : any, reject : any) {
	const data : any = response.data
	const code : any = data.code || 200
	// @ts-ignore
	const msg : string = errorCode[code] || data.detailMessage || data.msg || errorCode['default']
	if (code === 401) {
		// 调用handle401Error，并等待其完成
		handle401Error().then(() => {
			reject('无效的会话，或者会话已过期，请重新登录。');
		}).catch(() => {
			// 如果有异常发生，也应拒绝原始请求的Promise
			reject('处理401错误时出现异常');
		});
	} else if (code === 500) {
		reject(msg)
	} else if (code !== 200) {
		reject(msg)
	} else {
		resolve(data)
	}
}

function handleError(error : any, reject : any) {
	let { message } = error
	if (message === 'Network Error') {
		message = '后端接口连接异常'
	} else if (message.includes('timeout')) {
		message = '系统接口请求超时'
	} else if (message.includes('Request failed with status code')) {
		message = '系统接口' + message.substr(message.length - 3) + '异常'
	}
	toast(message)
	reject(error)
}

export default request
